package im

import (
	"time"
	"dhfshop/models/im"
	"dhfshop/models/org"
	"dhfshop/models/member"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type FormIdCacheController struct {
	base.BaseController
}

func (this *FormIdCacheController) Post() {
	var v im.FormIdCache
	this.ParseForm(&v)
	curRoleId := this.Ctx.Input.GetData("curRoleId").(int) 
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	v.MemberId = int64(this.Ctx.Input.GetData("curUserId").(int))
	valid := validation.Validation{}
	valid.Required(v.PartnerId, "partner_id")
	valid.Required(v.MemberId, "member_id")
	valid.Required(v.AppId, "app_id")    //外部获取的参数无效
	valid.Required(v.FormId, "form_id")
	valid.Required(v.Types, "types")
	valid.Required(v.Xid, "xid")
	passed, _ := valid.Valid(&v)
	if !passed {
	    this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	v.MaxCount = 1
	v.CurUseCount = 0
	if curRoleId == 2 {
	    if user, err := org.GetUserByUserId(v.MemberId); err == nil {
			v.OpenId = user.OpenID
			v.AppId = user.FollowAppId
		}
	}else{
	    if members, err := member.GetMemberById(v.MemberId); err == nil {
			v.OpenId = members.OpenID
			v.AppId = members.AppId
		}
	}
	v.ExpireAt = time.Now().UTC().Add(time.Hour*24*7)
	id, err := im.AddFormIdCache(&v)
	if err != nil{
		this.ServeError(err.Error())
		return
	}
	beego.Debug("FormIdCacheController AddFormIdCache:", id)
	rsp := struct {
		FormidCacheId int64     `json:"formid_cache_id"`
	    Created      time.Time  `json:"created"`
	}{FormidCacheId:id, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}	
